package com.bkhc.umc.auth.service;


import com.bkhc.common.exception.CustomException;
import com.bkhc.common.util.response.ResultCode;
import com.bkhc.common.util.response.ResultJson;
import com.bkhc.umc.auth.model.UserModel;
import com.bkhc.umc.entity.Role;
import com.bkhc.umc.entity.User;
import com.bkhc.umc.repository.RoleRepository;
import com.bkhc.umc.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author lb
 * @date 2021/4/27
 * @time 22:44
 */
@Component
public class UserAuthService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user == null) throw new CustomException(ResultJson.failure(ResultCode.NO_ACOUNT));
        if (!user.getStatus().equals( "1")) throw new CustomException(ResultJson.failure(ResultCode.LOGIN_ERROR));
        user.setRoles(roleRepository.findAllByUserIdAndStatus(user.getUserId(),user.getStatus()));
        List<GrantedAuthority> grantedAuthorities = mapToGrantedAuthorities(user.getRoles().stream().map(Role::getRoleCode).collect(Collectors.toList()));

        return new UserModel(user.getUserId(),user.getUsername(),user.getPassword(),grantedAuthorities);
    }

    private static List<GrantedAuthority> mapToGrantedAuthorities(List<String> authorities) {
        return authorities.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

}